package com.wzd.shoppingService.utils.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * @Description Feign配置
 * @Author ruan
 * @Date 2019-11-13 10:46
 **/
public class FeignConfig {

    @Bean
    public RequestInterceptor headerInterceptor() {

        return new RequestInterceptor() {

            @Override
            public void apply(RequestTemplate requestTemplate) {

                ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
                        .getRequestAttributes();
                HttpServletRequest request = attributes.getRequest();
                Enumeration<String> headerNames = request.getHeaderNames();

                if (headerNames != null) {
                    while (headerNames.hasMoreElements()) {
                        String name = headerNames.nextElement();
                        String values = request.getHeader(name);
                        if ("ACCESS_TOKEN".equals(name.toUpperCase()) || "DEBUG".equals(name.toUpperCase()) || "CONTTENT-TYPE".equals(name.toUpperCase())) {
                            requestTemplate.header(name, values);
                        }
                    }
                }
            }
        };
    }
}